/**
 * 
 */
package com.lemote.action.account;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lemote.action.BaseAction;
import com.lemote.core.HibernateUtils;
import com.lemote.core.PropertyFilter;
import com.lemote.entity.Group;
import com.lemote.entity.Model;
import com.lemote.entity.Permission;
import com.lemote.entity.Role;
import com.lemote.entity.User;
import com.lemote.exception.AppException;
import com.lemote.service.account.GroupService;
import com.lemote.service.account.PermissionService;
import com.lemote.service.account.RoleService;
import com.lemote.service.account.UserService;
import com.lemote.utils.CheckUtils;
import com.lemote.utils.CodeUtils;
import com.lemote.utils.Constant;
import com.lemote.utils.encode.EncodeUtils;

/**
 * @author wuhui
 * 
 *        下午04:16:49
 */
@Component("userAction")
public class UserAction extends BaseAction<User, UserService> {

	private ByteArrayInputStream inputStream;

	private String msg;

	private List<Long> checkedPermissionIds;// 页面中钩选的权限id列表

	private List<Long> checkedRoleIds;// 页面中钩选的角色id列表

	private List<Long> checkedGroupIds;// 页面中钩选的用户组id列表

	private PermissionService permissionService;

	private RoleService roleService;

	private GroupService groupService;

	private User user;

	@Override
	public String delete() throws AppException {

		if (ids != null && ids.length() > 0) {
			entityService.delete(CheckUtils.stringParse(ids));
		}
		return SUCCESS;
	}

	public String login() throws AppException {

		return SUCCESS;
	}

	/**
	 * 用户登陆
	 * 
	 * @return
	 * @throws AppException
	 */
	public String loginUser() throws AppException {
		String loginName = request.getParameter("name");
		String password = request.getParameter("password");
		String inputcode = request.getParameter("sofecode");
		String code = (String) request.getSession().getAttribute("code");
		if (CheckUtils.isEmpty(loginName) || CheckUtils.isEmpty(password)) {
			request.getSession().setAttribute("error", "*用户名或密码不能为空!");
			return "login";
		}
		try {
			user = entityService.login(loginName, EncodeUtils.md5(password));
		} catch (NoSuchAlgorithmException e) {
			throw new AppException("系统繁忙！");
		}
		if (CheckUtils.isNull(user) || CheckUtils.isNull(user.getId())) {
			request.getSession().setAttribute("error", "*用户名或密码不正确!");
			return "login";
		}
		if ("1".equals(user.getStatus())) {
			request.getSession().setAttribute("error", "*当前用户被禁用!");
			return "login";
		}
		if (code==null||!code.equalsIgnoreCase(StringUtils.trim(inputcode))) {
			request.getSession().setAttribute("error", "*验证码不正确!");
			return "login";
		}
		request.getSession().removeAttribute("error");
		request.getSession().setAttribute(Constant.SESSION_USER, user);
		request.getSession()
				.setAttribute("models", mergeModel(user.getRoles()));
		request.getSession().setAttribute("permissions", mergePermission(user));

		return SUCCESS;
	}

	/**
	 * 修改添加用户信息
	 */
	@Override
	public String input() throws AppException {
		prepareModel();
		checkedGroupIds = user.getGroupIds();
		return SUCCESS;
	}

	@Override
	public String list() throws AppException {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(request);
		page = entityService.search(page, filters);
		return SUCCESS;
	}

	@Override
	public void prepareModel() throws AppException {
		if (id != null) {
			user = entityService.get(id);
		} else {
			user = new User();
		}
	}

	@Override
	public String save() throws AppException {
		if (user != null) {
			HibernateUtils.mergeByCheckedIds(user.getGroups(), checkedGroupIds,
					Group.class);
			try {
				user.setPassword(EncodeUtils.md5(user.getPassword()));
			} catch (NoSuchAlgorithmException e) {
				throw new AppException();
			}
			if (user.getId() == null) {
				entityService.add(user);
			} else {
				update(user);
			}
			return GLOBALSUCCESS;
		}
		return ERROR;
	}

	public void update(User user) {
		User u = entityService.get(user.getId());
		u.setAddr(user.getAddr());
		u.setBirthday(user.getBirthday());
		u.setGroups(user.getGroups());
		u.setPassword(user.getPassword());
		u.setPhone(user.getPhone());
		u.setRealName(user.getRealName());
		u.setSex(user.getSex());
		u.setWorkCard(user.getWorkCard());
		entityService.update(u);
	}

	public User getModel() {

		return user;
	}

	@Autowired
	public void setEntityService(UserService userService) {
		this.entityService = userService;
	}

	public void setUser(User user) {

		this.user = user;
	}

	public User getUser() {
		return user;
	}

	/**
	 * 生成验证码
	 * 
	 * @return
	 * @throws AppException
	 */
	public String code() throws AppException {
		Map<String, Object> map = CodeUtils.makeCode();
		String code = (String) map.get("code");
		request.getSession().setAttribute("code", code);
		BufferedImage image = (BufferedImage) map.get("image");
		try {
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			ImageOutputStream imageOut = ImageIO
					.createImageOutputStream(output);
			ImageIO.write(image, "JPEG", imageOut);
			imageOut.close();
			inputStream = new ByteArrayInputStream(output.toByteArray());
		} catch (IOException e) {
			throw new AppException("验证码生成异常!");
		}
		return SUCCESS;
	}

	/**
	 * 退出登陆
	 */

	public String loginOut() {
		request.getSession().removeAttribute(Constant.SESSION_USER);
		return SUCCESS;
	}

	/**
	 * 权限操作
	 * 
	 */
	public String authorize() {
		if (id != null) {
			user = entityService.get(id);
			checkedPermissionIds = user.getPermissionIds();
			checkedRoleIds = user.getRoleIds();
		}
		return SUCCESS;
	}

	/**
	 * 权限操作
	 * 
	 */
	public String anthorizePermission() {
		if (id == null) {
			return ERROR;
		}
		user = entityService.get(id);
		HibernateUtils.mergeByCheckedIds(user.getRoles(), checkedRoleIds,
				Role.class);
		HibernateUtils.mergeByCheckedIds(user.getPermissions(),
				checkedPermissionIds, Permission.class);
		entityService.update(user);
		return GLOBALSUCCESS;
	}

	/**
	 * 合并权限
	 */
	public Set<Permission> mergePermission(User user) {
		Set<Permission> permissions = new HashSet<Permission>();
		List<Role> roles = user.getRoles();
		if (roles != null) {
			for (Role role : roles) {
				permissions.addAll(role.getPermissions());
			}
		}
		permissions.addAll(user.getPermissions());
		return permissions;
	}

	/**
	 * 合并模块
	 */
	public List<Model> mergeModel(List<Role> roles) {

		List<Model> models = new ArrayList<Model>();
		for (Role role : roles) {
			List<Model> ms = role.getModels();
			for (Model model : ms) {
				if (!models.contains(model)) {
					models.add(model);
				}
			}
		}

		return models;
	}

	/**
	 * 跳转至修改密码
	 */
	public String pwd() {

		return SUCCESS;
	}

	/**
	 * 
	 * 修改密码
	 */
	public String modifyPassword() throws AppException {
		if (id != null) {
			String pawd = request.getParameter("pawd");
			String repawd = request.getParameter("repawd");
			if (!CheckUtils.isEmpty(pawd) && !CheckUtils.isEmpty(repawd)
					&& pawd.equals(repawd)) {
				user = entityService.get(id);
				if (user != null) {
					try {
						user.setPassword(EncodeUtils.md5(pawd));
						entityService.update(user);
					} catch (NoSuchAlgorithmException e) {
						throw new AppException("加密异常!");
					}
				} else {
					throw new AppException("参数异常!");
				}
			}
		}
		return GLOBALSUCCESS;
	}

	/**
	 *验证工卡号是否唯一
	 */
	public String unique() {

		String workCard = request.getParameter("wc");
		Integer size = entityService.isLoginNameUnique(workCard);
		if (size <= 0) {
			this.msg = "N";
		} else {
			this.msg = "Y";
		}
		return SUCCESS;
	}

	/**
	 * input页面显示所有授权列表.
	 */
	public List<Permission> getAllPermissionList() {

		return permissionService.getAll();
	}

	/**
	 * input页面显示所有用户组列表.
	 */
	public List<Group> getAllGroupList() {

		return groupService.getAll();
	}

	/**
	 * input页面显示所有角色列表.
	 */
	public List<Role> getAllRoleList() {

		return roleService.getAll();
	}

	/**
	 * input页面显示用户拥有的授权.
	 */
	public List<Long> getCheckedPermissionIds() {
		return checkedPermissionIds;
	}

	/**
	 * input页面显示用户拥有的角色.
	 */
	public List<Long> getCheckedRoleIds() {
		return checkedRoleIds;
	}

	/**
	 * input页面显示用户拥有的用户组.
	 */
	public List<Long> getCheckedGroupIds() {
		return checkedGroupIds;
	}

	public void setCheckedPermissionIds(List<Long> checkedPermissionIds) {
		this.checkedPermissionIds = checkedPermissionIds;
	}

	public void setCheckedRoleIds(List<Long> checkedRoleIds) {
		this.checkedRoleIds = checkedRoleIds;
	}

	public void setCheckedGroupIds(List<Long> checkedGroupIds) {
		this.checkedGroupIds = checkedGroupIds;
	}

	/**
	 * @return the inputStream
	 */
	public ByteArrayInputStream getInputStream() {
		return inputStream;
	}

	@Autowired
	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}

	@Autowired
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	@Autowired
	public void setGroupService(GroupService groupService) {
		this.groupService = groupService;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

}
